﻿using com.winter.manager;
using UnityEngine;

namespace com.winter.pig
{
    public class Pig : MonoBehaviour
    {
        public enum pig_STATE
        {
            normal,
            hurt,
            dead
        }

        [Header("当前物体的状态")] public pig_STATE pigState = pig_STATE.normal;

        [Header("被撞死的速度")] public float maxSpeed = 10;
        [Header("被撞伤的速度")] public float minSpeed = 6;

        private SpriteRenderer spriteRenderer;

        [Header("被攻击物体受伤的图片")] public Sprite hurt;

        [Header("被攻击物体死亡后的爆炸特效")] public GameObject boom;

        [Header("被攻击物体死亡后的加分特效")] public GameObject score;

        public bool isPig;

        // Start is called before the first frame update
        void Start()
        {
            spriteRenderer = GetComponent<SpriteRenderer>();
        }


        private void OnCollisionEnter2D(Collision2D other)
        {
            if (other.relativeVelocity.magnitude > minSpeed && other.relativeVelocity.magnitude < maxSpeed)
            {
                // pig hurt
                spriteRenderer.sprite = hurt;
                pigState = pig_STATE.hurt;
                maxSpeed = (maxSpeed + minSpeed) / 2;
            }
            else if (other.relativeVelocity.magnitude > maxSpeed)
            {
                // pig die
                Dead();
            }

            // Debug.Log(other.relativeVelocity.magnitude);
        }

        private void Dead()
        {
            pigState = pig_STATE.dead;
            if (isPig)
            {
                GameManager.getInstance().pigs.Remove(this);
            }

            Instantiate(boom, transform.position, Quaternion.identity);

            GameObject pigScore = Instantiate(score, transform.position + new Vector3(0, 0.5f, 0), Quaternion.identity);
            Destroy(gameObject);
            Destroy(pigScore, 1.5f);
        }
    }
}